package com.kmxy.kmxy_base

import android.annotation.SuppressLint
import android.app.Activity
import android.content.*
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.PowerManager
import android.provider.Settings
import android.util.Log
import androidx.annotation.NonNull
import androidx.annotation.RequiresApi
import androidx.core.content.FileProvider
import com.amap.api.location.AMapLocation
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import org.json.JSONObject
import java.io.File


/** KmxyBasePlugin */
class KmxyBasePlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel
    private lateinit var mActivity: Activity

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "kmxy_base")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        when (call.method) {
            // 直接打电话
            "callPhone" -> {
                callPhone(call.arguments as String)
                result.success("成功")
            }
            // 忽略电池优化
            "requestIgnoreBatteryOptimizations" -> {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestIgnoreBatteryOptimizations()
                    result.success("成功")
                }
            }
            // 开启定位服务
            "startLocationService" -> {
                startLocationService(call.arguments as Boolean)
                result.success("成功")
            }
            // 停止定位服务
            "stopLocationService" -> {
                stopLocationService()
                result.success("成功")
            }
            // 设置开启悬浮窗
            "setSystemAlertWindow" -> {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    setSystemAlertWindow()
                    result.success("成功")
                }
            }
            // 判断是否开启悬浮窗
            "isSystemAlertWindow" -> {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    result.success(isSystemAlertWindow())
                }
            }
            // 是否忽略电池优化
            "isIgnoringBatteryOptimizations" -> {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    result.success(isIgnoringBatteryOptimizations())
                }
            }
            // 蒲公英地址
            "pgyerUrl" -> {
                result.success("https://www.pgyer.com")
            }
            // 判断应用程序是否安装
            "isAvilible" -> {
                result.success(isAvilible(call.arguments as String))
            }
            // 打开wps
            "openWps" -> {
                if (openWps(call.arguments as String)) {
                    result.success("成功")
                } else {
                    result.success("失败")
                }
            }

            // 安装apk
            "installApk" -> {
                if (installApk(call.arguments as String)) {
                    result.success("成功")
                } else {
                    result.success("失败")
                }
            }
            // 判断CPU是否是arm64-v8a
            "isArm64V8a" -> {
                result.success(isArm64V8a())
            }
            // 读取APK文件的版本号
            "getApkVersionName" -> {
                result.success(getApkVersionName(call.arguments as String))
            }

            else -> result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
        if (locationChangeBroadcastReceiver != null) mActivity.unregisterReceiver(
            locationChangeBroadcastReceiver
        )
    }

    @SuppressLint("WrongConstant", "UnspecifiedRegisterReceiverFlag")
    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        mActivity = binding.activity
        // 保护广播
        val intentFilter = IntentFilter(Utils.LOCATION_BRODECAST_INTENT_ACTION_NAME)
        // 添加Android 14适配代码
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            mActivity.registerReceiver(
                locationChangeBroadcastReceiver,
                intentFilter,
                Context.RECEIVER_EXPORTED
            )
        } else {
            mActivity.registerReceiver(
                locationChangeBroadcastReceiver,
                intentFilter
            )
        }
    }

    override fun onDetachedFromActivityForConfigChanges() {
        TODO("Not yet implemented")
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        TODO("Not yet implemented")
    }

    override fun onDetachedFromActivity() {
        TODO("Not yet implemented")
    }

    /**
     * 直接拨打电话
     */
    private fun callPhone(num: String) {
        val action = Intent.ACTION_CALL
        val intent = Intent(action)
        intent.data = Uri.parse("tel:$num")
        mActivity.startActivity(intent)
    }

    /**
     * 忽略电池优化
     */
    @RequiresApi(Build.VERSION_CODES.M)
    private fun requestIgnoreBatteryOptimizations() {
        try {
            val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
            intent.data = Uri.parse("package:" + mActivity.packageName)
            mActivity.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 是否忽略电池优化
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private fun isIgnoringBatteryOptimizations(): Boolean {
        var isIgnoring = false
        val powerManager: PowerManager? =
            mActivity.getSystemService(Context.POWER_SERVICE) as PowerManager?
        if (powerManager != null) {
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(mActivity.packageName)
        }
        return isIgnoring
    }

    /**
     * 设置开启悬浮窗
     */
    @RequiresApi(Build.VERSION_CODES.M)
    private fun setSystemAlertWindow() {
        if (!isSystemAlertWindow()) {
            val intent = Intent()
            intent.action = Settings.ACTION_MANAGE_OVERLAY_PERMISSION
            intent.data = Uri.parse("package:${mActivity.packageName}")
            mActivity.startActivity(intent)
        }
    }

    /**
     * 判断是否开启悬浮窗
     */
    @RequiresApi(Build.VERSION_CODES.M)
    private fun isSystemAlertWindow(): Boolean {
        return Settings.canDrawOverlays(mActivity)
    }

    /**
     * 定位广播通知过来的定位数据
     */
    private val locationChangeBroadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (action == Utils.LOCATION_BRODECAST_INTENT_ACTION_NAME) {
                if (intent.getBooleanExtra("isLocationAMap", true)) {
                    var locationResult = intent.getStringExtra("resultJson").toString()
                    val errorCode = intent.getIntExtra("errorCode", 0)
                    val gpsAccuracyStatus = intent.getIntExtra("gpsAccuracyStatus", -1)
                    val jsonObject = JSONObject(locationResult)
                    jsonObject.put("gpsAccuracyStatus", gpsAccuracyStatus)
                    locationResult = jsonObject.toString()
                    if (errorCode == AMapLocation.LOCATION_SUCCESS) {
//                    Log.e("mWifiAutoCloseDelegate", "网路正常连接")
//                    Log.e("mWifiAutoCloseDelegate", locationResult.toString())
                        channel.invokeMethod("locationServiceCallback", locationResult)
                    } else {
//                    Log.e("mWifiAutoCloseDelegate", "网路连接失败")
                        // 唤醒屏幕
                        PowerManagerUtil.getInstance().wakeUp(mActivity)
                    }
                } else {
                    val errorCode = intent.getIntExtra("errorCode", 0)
                    if (errorCode == 0) {
                        channel.invokeMethod(
                            "GpslocationServiceCallback",
                            intent.getStringExtra("result").toString()
                        )
                    } else {
                        // 唤醒屏幕
                        PowerManagerUtil.getInstance().wakeUp(mActivity)
                    }
                }

            }
        }
    }

    /**
     * 开始定位服务
     */
    private fun startLocationService(isLocationAMap: Boolean) {
        mActivity.startService(
            Intent(
                mActivity,
                LocationService::class.java
            ).putExtra("isLocationAMap", isLocationAMap)
        )
        LocationStatusManager.getInstance().resetToInit(mActivity)
    }

    /**
     * 关闭服务
     * 先关闭守护进程，再关闭定位服务
     */
    private fun stopLocationService() {
        mActivity.sendBroadcast(Utils.getCloseBrodecastIntent())
        LocationStatusManager.getInstance().resetToInit(mActivity)
    }


    /**
     * 判断应用程序是否安装
     */
    private fun isAvilible(packageName: String): Boolean {
        val packageManager = mActivity.packageManager
        // 获取所有已安装程序的包信息
        val pinfo = packageManager.getInstalledPackages(0)
        for (i in pinfo.indices) {
            if (pinfo[i].packageName.equals(packageName, ignoreCase = true)) return true
        }
        return false
    }

    /**
     * 判断安装包是否存在
     */
    private fun openWps(filePath: String): Boolean {
        val intent = Intent()
        val bundle = Bundle()
        bundle.putString("OpenMode", "ReadOnly") // 只读模式
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.action = Intent.ACTION_VIEW
        intent.setClassName(
            "cn.wps.moffice_eng",
            "cn.wps.moffice.documentmanager.PreStartActivity2"
        )
        var uri = Uri.parse("file://$filePath");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(
                mActivity,
                "${mActivity.packageName}.fileprovider",
                File(filePath)
            )
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) // 表示对目标应用临时授权该Uri所代表的文件
        }
        intent.data = uri
        intent.putExtras(bundle)
        try {
            mActivity.startActivity(intent)
        } catch (e: ActivityNotFoundException) {
            e.printStackTrace()
            return false
        }
        return true
    }


    private fun installApk(apkPath: String): Boolean {
        try {
            val intent = Intent(Intent.ACTION_VIEW)
            val apkFile: File = File(apkPath)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                val uri = FileProvider.getUriForFile(
                    mActivity,
                    mActivity.packageName + ".fileprovider",
                    apkFile
                )
                intent.setDataAndType(uri, "application/vnd.android.package-archive")
            } else {
                intent.setDataAndType(
                    Uri.fromFile(apkFile),
                    "application/vnd.android.package-archive"
                )
            }
            mActivity.startActivity(intent)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            return false
        }
        return true
    }

    /**
     * 判断设备是否支持arm64-v8a架构
     * @return true if device supports arm64-v8a, false otherwise
     */
    fun isArm64V8a(): Boolean {
        // 对于API 21及以上，使用SUPPORTED_ABIS
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // API 21+ 使用SUPPORTED_ABIS
            Build.SUPPORTED_ABIS.contains("arm64-v8a")
        } else {
            // 旧版本使用CPU_ABI和CPU_ABI2
            "arm64-v8a" == Build.CPU_ABI || "arm64-v8a" == Build.CPU_ABI2
        }
    }

    /**
     * 读取APK文件的版本号
     */
    fun getApkVersionName(apkFilePath: String): String {
        // 检查文件是否存在
        val apkFile = File(apkFilePath)
        if (!apkFile.exists() || !apkFile.isFile) {
            return ""
        }

        val packageManager: PackageManager = mActivity.packageManager

        // 解析APK文件获取包信息
        val packageInfo: PackageInfo? = packageManager.getPackageArchiveInfo(
            apkFilePath,
            PackageManager.GET_ACTIVITIES or PackageManager.GET_SERVICES
        )

        if (packageInfo == null) {
            return ""
        }

        return packageInfo.versionName
    }
}
